package LeetCode.LC200;

/**
 * @author corn
 * @create 2020-07-30-19:51
 */


/**
 * 200. 岛屿数量
 * 给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
 * 岛屿总是被水包围，并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
 * 此外，你可以假设该网格的四条边均被水包围。
 *
 * 解题思想：
 *      遍历：是同一个岛的就把‘1’变成‘0’
 *
 */
public class NumIslands {
    public static void main(String[] args) {
//        char[][] grid = {{'1','1','1','1','0'},
//                         {'1','1','0','1','0'},
//                         {'1','1','0','0','1'},
//                         {'0','0','0','1','0'}};
//        char[][] grid = {};
        char[][] grid = {{'1','1','1'},
                         {'0','1','0'},
                         {'1','1','1'},};
        Solution solution = new Solution();
        int i = solution.numIslands(grid);
        System.out.println(i);
    }
}
class Solution {
    private int count = 0;
    private int col = 0;//列长
    private int row = 0;//行长
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        col = grid.length;
        row = grid[0].length;
        for (int i = 0; i < grid.length; i++) {
            for(int j = 0 ; j < grid[i].length ; j++){
                if(grid[i][j] == '1'){
                    oneToZero(grid , i , j);
                    count += 1;
                }
            }
        }
        return count;
    }
    public void oneToZero(char[][] grid,int i,int j){
        if( i < 0 || i >= col || j < 0 || j>= row || grid[i][j] == '0'){
            return;
        }
        grid[i][j] = '0';
        oneToZero(grid,i + 1, j);
        oneToZero(grid,i - 1, j);
        oneToZero(grid,i, j + 1);
        oneToZero(grid,i, j - 1);
    }
}